package com.qf.common.core.exception;

import com.qf.common.core.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * --- 缘分让我们相遇乱世以外 ---
 *
 * @author SJY
 * 2024/12/26
 * 全局异常处理类
 * 一搬异常信息需要存入日志中，便于后期排查问题
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(CommonException.class)
    public R commonExceptionHandler(CommonException e) {
        log.error(e.getMsg());
        e.printStackTrace();
        return R.fail(e.getMsg());
    }

    @ExceptionHandler(Exception.class)
    public R exceptionHandler(Exception e) {
        log.error(e.getMessage());

        return R.fail("未知异常,请联系管理员");
    }
    // 验证框架异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R exceptionHandler2(MethodArgumentNotValidException e) {
        StringBuilder sb = new StringBuilder();
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        String message = allErrors.stream().map(s -> s.getDefaultMessage()).collect(Collectors.joining(";"));
        return R.fail(message);
    }

    @ExceptionHandler({ConstraintViolationException.class, BindException.class})
    public R validateException(Exception ex, HttpServletRequest request) {
        ex.printStackTrace();
        String msg = null;
        if(ex instanceof ConstraintViolationException){
            ConstraintViolationException constraintViolationException =
                    (ConstraintViolationException)ex;
            Set<ConstraintViolation<?>> violations =
                    constraintViolationException.getConstraintViolations();
            ConstraintViolation<?> next = violations.iterator().next();
            msg = next.getMessage();
            System.out.println("校验失败："+msg);
        }else if(ex instanceof BindException){
            BindException bindException = (BindException)ex;
            msg = bindException.getBindingResult().getFieldError().getDefaultMessage();
            System.out.println("校验失败："+msg);

        }
        return R.fail(msg);
    }
}
